package com.winai.launcher.view.timeManager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.view.WheelView;
import com.google.gson.Gson;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.bean.db.AlarmClockBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.override.RandomId;
import com.winai.launcher.override.dialog_global.GlobalDialog;
import com.winai.launcher.utils.AlarmManagerUtil;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/12/13 0013
 * 说明：添加闹钟
 */
public class AddClockActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.tv_repeat)
    TextView tvRepeat;
    @BindView(R.id.fragmen_fragment)
    FrameLayout frameFragment;
    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.et_tag)
    TextView etTag;

    private TimePickerView pvTime;
    private AlarmClockBean mAlarmClockBean = new AlarmClockBean();
    private Calendar calendar;
    private String time;
    private boolean editEnable = false;
    private AlarmClockBean bean;
    private boolean change = false;//是否改过
    private GlobalDialog.Builder tipDialog;
    private final int CODE_RESULT = 0x1211;
    private final int CODE_RESULT_TAG = 0x1222;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_clock);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initView();
        initTimePicker();
        pvTime.show();
        initListener();
    }

    private void initObject() {
        strTitle.setText("编辑闹钟");

        calendar = Calendar.getInstance();
        editEnable = getIntent().getBooleanExtra("editEnable", false);
        bean = (AlarmClockBean) getIntent().getSerializableExtra("alarmClockBean");

        tipDialog = new GlobalDialog.Builder(mContext)
                .setTitle("提示")
                .setContent("确定退出？将不保存编辑记录")
                .setConfirmText("不保存")
                .setCancelText("取消")
                .setOnConfirmClickListener(new GlobalDialog.OnConfirmClickListener() {
                    @Override
                    public void onClick(GlobalDialog mGlobalDialog, View v) {
                        finish();
                    }
                });

    }

    private void initView() {
        if (editEnable) {//编辑进来的，带出数据
            tvRepeat.setText(bean.getWeek());
            etTag.setText(bean.getRemark());
        }
    }

    private void initListener() {
        etTag.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                change = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void initTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        if (editEnable) {
            String[] split = bean.getTime().split(":");
            if (split.length >= 2) {
                String s = split[0];
                String ss = split[1];
                int hours = Integer.parseInt(s);
                int minute = Integer.parseInt(ss);
                selectedDate.set(2019, 0, 1, hours, minute);
            }
        }
        Calendar startDate = Calendar.getInstance();
        startDate.set(2018, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2099, 12, 31);
        //时间选择器
        pvTime = new TimePickerBuilder(mContext, (date, v) -> {//选中事件回调
            time = getTime(date);
            String[] split = time.split(":");
            int hourOfDay = Integer.parseInt(split[0]);
            int minute = Integer.parseInt(split[1]);
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        })
                .setLayoutRes(R.layout.picker_time, v -> {

                })
                .setType(new boolean[]{false, false, false, true, true, false})
                .setLabel("", "", "", "", "", "") //设置空字符串以隐藏单位提示   hide label
                .setDividerColor(getResources().getColor(R.color.colorText))
                .setContentTextSize(40)
                .setItemVisibleCount(5)
                .isAlphaGradient(true)
                .setGravity(Gravity.CENTER)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(frameFragment)//非dialog模式下,设置ViewGroup, pickerView将会添加到这个ViewGroup中
                .setOutSideColor(0x00000000)
                .setOutSideCancelable(false)
                .setTextColorCenter(getResources().getColor(R.color.colorText))
                .setTextColorOut(Color.parseColor("#888888"))
                .setDividerType(WheelView.DividerType.BACKGROUND)
                .build();

        pvTime.setKeyBackCancelable(false);//系统返回键监听屏蔽掉
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CODE_RESULT:
                    if (data != null) {
                        String repeat = data.getStringExtra("repeat");
                        tvRepeat.setText(repeat);
                        change = true;
                    }
                    break;
                case CODE_RESULT_TAG:
                    if (data != null) {
                        String tag = data.getStringExtra("tag");
                        etTag.setText(tag);
                        change = true;
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.iv_save, R.id.iv_cancel, R.id.tv_repeat, R.id.et_tag})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (editEnable && change) {
                    tipDialog.show();
                } else {
                    finish();
                }
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.iv_save:
                pvTime.returnData();
                if (editEnable) {
                    List<AlarmClockBean> oldAlarmList =
                            LitePal.where("alarmId = ?", bean.getId()).find(AlarmClockBean.class);
                    if (change) {
                        for (AlarmClockBean bb : oldAlarmList) {
                            //删除原来的闹钟
                            AlarmManagerUtil.cancelAlarm(mContext, bb);
                        }
                    }
                    boolean success = mAlarmClockBean.setTime(time)
                            .setWeek(tvRepeat.getText().toString())
                            .setRemark(etTag.getText().toString())
                            .setOpen(true)
                            .saveOrUpdate("alarmId = ?", bean.getId());
                    if (success) {
                        List<AlarmClockBean> alarmClockBeans =
                                LitePal.where("alarmId = ?", bean.getId()).find(AlarmClockBean.class);
                        for (AlarmClockBean bb : alarmClockBeans) {
                            if (bb.isOpen()) {
                                AlarmManagerUtil.setAlarm(mContext, bb);
                                // 通知AI修改闹钟
                                if (oldAlarmList != null && oldAlarmList.size() > 0) {
                                    notifyReceiver(oldAlarmList.get(0), bb);
                                }
                            } else {
                                AlarmManagerUtil.cancelAlarm(mContext, bb);
                            }
                        }
                    }
                } else {
                    RandomId randomId = new RandomId();
                    String id = randomId.randomId();
                    boolean success = mAlarmClockBean.setId(id)
                            .setTime(time)
                            .setWeek(tvRepeat.getText().toString())
                            .setRemark(etTag.getText().toString())
                            .setOpen(true)
                            .save();
                    if (success) {
                        List<AlarmClockBean> alarmClockBeans =
                                LitePal.where("alarmId = ?", id).find(AlarmClockBean.class);
                        for (AlarmClockBean bb : alarmClockBeans) {
                            //删除闹钟
                            LitePal.deleteAll(AlarmClockBean.class, "alarmId = ?", bb.getId());
                            if (bb.isOpen()) {
//                                AlarmManagerUtil.setAlarm(mContext, bb);
                                // 通知AI添加闹钟
                                notifyReceiver(bb);
                            } else {
                                AlarmManagerUtil.cancelAlarm(mContext, bb);
                            }
                        }
                    }
                }
                GlobalPublisher.Notify(GlobalPublisher.CHANGE_ALARM_CLOCK);
                finish();
                break;
            case R.id.iv_cancel:
                tipDialog.show();
                break;
            case R.id.tv_repeat:
                //重复
                Intent intent = new Intent(mContext, AlarmRepeatActivity.class);
                intent.putExtra("repeat", tvRepeat.getText().toString());
                startActivityForResult(intent, CODE_RESULT);
                break;
            case R.id.et_tag:
                //标签
                Intent intent2 = new Intent(mContext, AlarmTagActivity.class);
                intent2.putExtra("tag", etTag.getText().toString());
                startActivityForResult(intent2, CODE_RESULT_TAG);
                break;
        }
    }

    /**
     * 说明：修改闹钟
     */
    private void notifyReceiver(AlarmClockBean oldAlarm, AlarmClockBean newAlarm) {
        String oldAlarmJSON = new Gson().toJson(oldAlarm);
        String newAlarmJSON = new Gson().toJson(newAlarm);
        Intent intent = new Intent();
        intent.setAction(Constant.SpeechActionReminderUpdate);
        intent.putExtra("oldAlarmJSON", oldAlarmJSON);
        intent.putExtra("newAlarmJSON", newAlarmJSON);
        mContext.sendBroadcast(intent);
    }

    /**
     * 说明：通知添加闹钟
     */
    private void notifyReceiver(AlarmClockBean alarm) {
        String alarmJSON = new Gson().toJson(alarm);
        Intent intent = new Intent();
        intent.setAction(Constant.SpeechActionReminderAdd);
        intent.putExtra("alarmJSON", alarmJSON);
        mContext.sendBroadcast(intent);
    }
}
